<template>
  <div>
    <!-- <my-header :data="headerData"/ -->
    <el-row class="top" style="padding:10px 10px 0 10px;">
      <el-col :span="12">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/user' }" >客户中心</el-breadcrumb-item >
          <el-breadcrumb-item ><a href="/user/show">{{pName}}</a></el-breadcrumb-item >
        </el-breadcrumb>
      </el-col>
      <el-col :span="12" align="right" >
        <el-button type="primary" icon="el-icon-folder-checked" @click="downloadAllPhoto">全部下载</el-button>
        </el-col >
    </el-row>
    <el-divider></el-divider>
    <el-row class="content">
      <!-- <div> -->
      <div v-for="(url,index) in urls" :key="index">
        <el-button class="edit" type="text" @click="edit(url.pics_big_url,index,url.pics_id)"><i class="el-icon-s-open"></i></el-button>
        <el-image
          style="width: 100%;height: auto;"
          :src="url.pics_mid_url"
          :lazy="true"
          :preview-src-list="getSrcList(index)">
        </el-image>
      </div>
    </el-row>
  </div>
</template>
<script>
import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}
export default {
  data() {
    return {
      urls: [],
      // 意见数组
      masker: [],
      // 涂鸦数组
      imgPlant: [],
      // 大图预览
      preImg: [],
      // id
      id: '',
      // 数据
      data: {},
      // 图库名称
      pName: '',
      // 全部图片
      allPic: []
    }
  },

  mounted() {
    var urlData = this.$route.query
    this.id = urlData.id
    this.pName = urlData.name
    this.getData()
  },
  methods: {
    // 大图浏览在当前index
    getSrcList(index) {
      return this.preImg.slice(index).concat(this.preImg.slice(0, index))
    },
    async getData() {
      const { data } = await this.$http.get(`goods/${this.id}`)
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.urls = data.data.pics
      this.data = data.data
      // 把照片加进大图预览数组
      for (var l in this.urls) {
        this.preImg.push(this.urls[l].pics_big_url)
        // console.log(this.preImg)
      }
      if (data.data.goods_big_logo === null) {
        for (var i in this.urls) {
          console.warn(i)
          var maskerObj = {
            masker: '',
            id: this.urls[i].pics_id
          }
          this.masker.push(maskerObj)
        }
        const maskerJson = JSON.stringify(JSON.stringify(this.masker))
        this.data.goods_big_logo = maskerJson
        // console.log(this.data, '获取到的数据')
        const { data: editData } = await this.$http.put(`goods/${this.id}`, this.data)
        if (editData.meta.status !== 200) return this.$message.error('数据获取失败')
        window.sessionStorage.setItem('maskerJson', maskerJson)
      } else {
        window.sessionStorage.setItem('maskerJson', data.data.goods_big_logo)
      }
      if (data.data.goods_small_logo === null) {
        for (var j in this.urls) {
          console.warn(j)
          var plantObj = {
            plantData: '',
            id: this.urls[j].pics_id
          }
          this.imgPlant.push(plantObj)
        }
        const imgPlantJson = JSON.stringify(JSON.stringify(this.imgPlant))
        this.data.goods_small_logo = imgPlantJson
        // console.log(this.data, '获取到的数据')
        const { data: editData } = await this.$http.put(`goods/${this.id}`, this.data)
        if (editData.meta.status !== 200) return this.$message.error('数据获取失败')
        window.sessionStorage.setItem('PlantJson', imgPlantJson)
      } else {
        window.sessionStorage.setItem('PlantJson', data.data.goods_small_logo)
      }
    },
    edit(url, index, picsId) {
      window.sessionStorage.setItem('photoUrl', url)
      if (url === null) return false
      this.$router.push(`/user/edit?id=${this.id}&index=${index}&picId=${picsId}`)
    },
    // 下载全部图片
    downloadAllPhoto() {
      // console.log(this.urls, '=====urls')
      for (var i in this.urls) {
        this.allPic.push(this.urls[i].pics_big_url)
      }
      // console.log(this.allPic, '====allpics')
      var time = setTimeout(() => {
        this.handleBatchDownload()
        clearTimeout(time)
      }, 600)
    },
    handleBatchDownload() {
      const data = this.allPic // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
      const zip = new JSZip()
      const cache = {}
      const promises = []
      data.forEach(item => {
        const promise = getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
          const arrname = item.split('/')
          const filename = arrname[arrname.length - 1] // 获取文件名
          zip.file(filename, data, { binary: true }) // 逐个添加文件
          cache[filename] = data
        })
        promises.push(promise)
      })
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
          FileSaver.saveAs(content, this.pName + this.id + '.zip') // 利用file-saver保存文件
        })
      })
    },
    downs() {

    }
  }
}
</script>
<style lang="less" scoped>
.top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 30px;
}
.content {
  width: 100%;
  font-family: 'Lato', Calibri, Arial, sans-serif;
  padding: 0 0 0 10px;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // flex-wrap: wrap;
  column-count: 4;
  column-gap: 0;
  div{
    width: 95%;
    // padding: 5px;
    position: relative;
    .el-image{
    display: block;
    height: auto;
    }
    .edit{
      position: absolute;
      font-size: 20px;
      width:40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      top:7%;
      right: 2%;
      z-index: 100;
      background: rgba(255, 255, 255, 0.5);
    }
    .edit:hover{
      font-size: 35px;
      width: 60px;
      height: 60px;
      background: rgba(255, 255, 255, 1);
      transition: 0.5s;
    }
  }
}
/deep/.el-divider{
  margin: 5px 0 !important;
}
</style>
